<?php

if(isset($_GET['task']) and $_GET['task']=="addform")
	include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/headerlist.inc');
else
	include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/header.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/comp.inc');
include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/fcs.php');
?>

</script>

<?php


if(isset($_GET['task']))
{
		if(!$link=mysql_connect("localhost",$user,$pass))
			die("Error in Database Connection");

		if(!mysql_select_db("bs"))
			echo("Error in Database Selection");

		if($_GET['task']=="addform")
		{
?>

				| <a href="trans.php">Transaction </a> | Payment</div>
				<h3>Payment Entry<?php echo $_GET['task']?></h3>
				<table cellpadding="3" class="list">
				<form name="addform" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
				<tr><td><label>For Ledger</label></td></tr>
				<tr><td><select name="ldname" size="30" onblur="addform.submit()">
				<?php 		
				//DIPLAY ALL LEDGER EXCEPT CASH OR BANK
				
				$count=0;
				$resultmain=mysql_query("select * from bs_groups where under='00'");
				if(!$resultmain)
						echo("Error in Query Execution");
	
				while($arrmain=mysql_fetch_array($resultmain))
				{
						extract_ledger_except_cash_bank($arrmain['id']);
				}
				if($count==0)
						echo ("<option value='nothing'>Create Party Ledgers First</option>");
				?>
				</select>
			    </td></tr>
				<tr><td align="center"><input type="submit" value="Select" align="absmiddle" /></td></tr>
				<input type="hidden" name="task" value="addform2" />
				</form>
				</table>
			
		
<?php
		}//end of add form
		
		
		if($_GET['task']=="edit_form")
		{
		
				$pid=$_GET['pid'];

				$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_payment_book where id='{$pid}'");
				if(!$result)
					echo("Error in Query Execution");
				$arr=mysql_fetch_array($result);
		
				$date=$arr['date'];
				$amount=(int)$arr['amount'];
				$description=$arr['description'];
				$pldid=$arr['source_ledger_id'];						
				$ldid=$arr['ledger_id'];
		
							$result=mysql_query("select ldname from bs_ledgers where id='{$ldid}'");
							if(!$result)
									echo("Error in Query Execution");
							$arr=mysql_fetch_array($result);
				
				
			
				
?>				
							| <a href="trans.php">Transaction </a> | Payment	</div>
							<h3>Edit Payment Entry For Ledger :  <?php echo $arr['ldname'] ?> | <a href="payment_trans.php?task=delete&pid=<?php echo $pid?>">Delete</a></h3>

							<table class="main">
							<form name="addform2_common_for_all" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
							<tr><td><label>To : Ledger </label> </td><td><select name="pldid">
<?php
							//CASH ACCOUNT
							$count=0;
							$result=mysql_query("select * from bs_groups where gpname='Cash-in-hand'");
							if(!$result)
									echo("Error in Query Execution");
							$arr=mysql_fetch_array($result);
							extract_ledger_with_balance_wc($arr['id'],$pldid);
							//BANK ACCOUNT
							$result=mysql_query("select * from bs_groups where gpname='Bank Account'");
							if(!$result)
									echo("Error in Query Execution");
							$arr=mysql_fetch_array($result);
							extract_ledger_with_balance_wc($arr['id'],$pldid);
									
?>
							</select></td></tr>
							<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo $date?>" /></td></tr>
							<tr><td><label>Amount</label></td><td><input type="text" name="amount" value="<?php echo $amount?>" /> Rs</td></tr>
 							<tr><td><label>Description</label></td><td><textarea name="desc" rows="4"><?php echo $description?></textarea></td></tr>
							<tr><td><input type="submit" value="Update" /></td></tr>
							<input type="hidden" name="pid" value="<?php echo $pid ?>" />
							<input type="hidden" name="task" value="edit_common_for_all" />
							</form>
							</table>
				
<?php

		}//end of edit form
		
	if($_GET['task']=="delete")
	{
?>
	| <a href="trans.php">Transaction </a> | Payment Book	</div>
		<h3>Payment Book Transaction Deletion</h3>

<?php	
		$succ=1;
		
		$pid=$_GET['pid'];

		$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_payment_book where id='{$pid}'");
		if(!$result)
				echo("Error in Query Execution");
		$previous=mysql_fetch_array($result);
		
		
		
		//delete in ledger_id

					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$ldname} where voucher_type='PAYMENT' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$ldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				

		
		//delete in purchase_ledger_id
		
					//1. extract previous ldname
					$result=mysql_query("select ldname from bs_ledgers where id='{$previous['source_ledger_id']}'");
					if(!$result)
							echo("Error in Query Execution");
					$arr=mysql_fetch_array($result);
					$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
					//2. delete from previous ldname
						//first fetch the id!!!
						$result=mysql_query("select id from {$pldname} where voucher_type='PAYMENT' and voucher_id='{$pid}' ");
						if(!$result)
						{
							echo("Error");
							$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
						if(!$result)
						{
							echo("Error in previous Ledger deletion".mysql_error());
							$succ=0;
						}				
		
		//delete in payment book
						$result=mysql_query("delete from bs_payment_book where id='{$pid}'" );			
						if(!$result)
						{
							echo("Error in payment book deletion".mysql_error());
							$succ=0;
						}
			
		if($succ==1)
			echo"<br>SuccessFul";
		else
			echo"<br>Operation Fail";
			
				
	}//end of delete operation
		
			
}

else if(isset($_POST['task']))
{
?>


<?php		

		if(!$link=mysql_connect("localhost",$user,$pass))
				die("Error in Database Connection");

		if(!mysql_select_db("bs"))
				echo("Error in Database Selection");
		

		if($_POST['task']=="addform2")
		{	
				if(empty($_POST['ldname']))
						header("Location: http://localhost/bs/payment_trans.php?task=addform");
				
				else //common_for_all
				{
?>				
			
								| <a href="trans.php">Transaction </a> | Payment	</div>
								<h3>Payment Entry For Ledger :  <?php echo $_POST['ldname'] ?></h3>

							<table class="main">
							<form name="addform2_common_for_all" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
							<tr><td><label>To : Ledger </label> </td><td><select name="pldname">
<?php
							//CASH ACCOUNT
							$count=0;
							$result=mysql_query("select * from bs_groups where gpname='Cash-in-hand'");
							if(!$result)
									echo("Error in Query Execution");
							$arr=mysql_fetch_array($result);
							extract_ledger_with_balance($arr['id']);
							//BANK ACCOUNT
							$result=mysql_query("select * from bs_groups where gpname='Bank Account'");
							if(!$result)
									echo("Error in Query Execution");
							$arr=mysql_fetch_array($result);
							extract_ledger_with_balance($arr['id']);
									
?>
							</select></td></tr>
							<tr><td><label>Date</label> </td><td> <input type="text" name="date" size="12" value="<?php echo date("d-m-Y");?>" /></td></tr>
							<tr><td><label>Amount</label></td><td><input type="text" name="amount" value="0" /> Rs</td></tr>
 							<tr><td><label>Description</label></td><td><textarea name="desc" rows="4"></textarea></td></tr>
							<tr><td><input type="submit" value="Add" /></td></tr>
							<input type="hidden" name="ldname" value="<?php echo $_POST['ldname'] ?>" />
							<input type="hidden" name="task" value="common_for_all" />
							</form>
							</table>
<?php
		
					
		
				}//END OF ADDFORM 2 FOR COMMON_FOR_ALL

		
	}//END OF POST TASK=ADDFORM2
	else
	{
	
	
				$valid=1;
				//VALIDATING DATE
				$datearr=explode("-",$_POST['date']);
				if(!ereg("^[0-3]?[0-9][\./\-][0-1]?[0-9][\./\-]20[0-9][0-9]$",$_POST['date']) or !checkdate($datearr[1],$datearr[0],$datearr[2]))
				{
						echo "Check Your Input Date<br>";
						$valid=0;
				}
				else
						$date=date("Y-m-d",mktime(0,0,0,$datearr[1],$datearr[0],$datearr[2]));

				//VALIDATING AMOUNT
				$amount=(int)$_POST['amount'];
				
				if(!ereg("^[0-9]+$",$_POST['amount']) or ($amount=(int)$_POST['amount'])==0 )
				{
					echo "<br>Check Your Amount Input<br>";
					$valid=0;
				}

				
				// AVOID NEGATIVE CASH
				if($_POST['task']!="edit_common_for_all")
				{
?>
						| <a href="trans.php">Transaction </a> | Payment	</div>
						<h3>Payment Entry For Ledger :  <?php echo $_POST['ldname'] ?></h3>

<?php						
						if(!is_negative_cash_allowed($_POST['pldname']))
						{
								$ledger="bs_ledger_".ereg_replace(" ","_",$_POST['pldname']);
								$result=mysql_query("select (SUM(debit)-SUM(credit)) as balance from {$ledger}");
								if(!$result)
										echo "Internal Select Query Error".mysql_error();
								$arr=mysql_fetch_array($result);
							
								$cashbalance=$arr['balance'];
	
								if($cashbalance<$amount)
								{
										echo "<br>Negative Cash Balance in Credit Side: {$cashbalance} Rs. ";
										echo "<br>Negative Cash is not Allowed in Cash and Bank Accounts ";					
										$valid=0;
								}
						}
				}
				else
				{
						$pid=$_POST['pid'];
						
								$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_payment_book where id='{$pid}'");
								if(!$result)
										echo("Error in Query Execution");
								$previous=mysql_fetch_array($result);
						$pldid=$previous['source_ledger_id'];
						$ldid=$previous['ledger_id'];
						
						$new_pldid=$_POST['pldid'];
						
						if($pldid==$new_pldid)
							$plus_this_entry=$previous['amount'];
						else
							$plus_this_entry=0;
						
								$result=mysql_query("select ldname from bs_ledgers where id='{$new_pldid}'");
								if(!$result)
										echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
						$pldname=$arr['ldname'];
						
											
								$result=mysql_query("select ldname from bs_ledgers where id='{$ldid}'");
								if(!$result)
										echo("Error in Query Execution");
								$arr=mysql_fetch_array($result);
	
?>						
					| <a href="trans.php">Transaction </a> | Payment	</div>
					<h3>Payment Entry For Ledger :  <?php echo $arr['ldname'] ?></h3>
					
<?php
						//I have to add the amount in balance that is in current entry with pid
						if(!is_negative_cash_allowed($pldname))
						{
								$ledger="bs_ledger_".ereg_replace(" ","_",$pldname);
								$result=mysql_query("select (SUM(debit)-SUM(credit)) as balance from {$ledger}");
								if(!$result)
										echo "Internal Select Query Error".mysql_error();
								$arr=mysql_fetch_array($result);
							
								$cashbalance=$arr['balance']+$plus_this_entry;
	
								if($cashbalance<$amount)
								{
										echo "<br>Negative Cash Balance in Credit Side: {$arr['balance']} Rs. ";
										echo "<br>Negative Cash is not Allowed in Cash and Bank Accounts ";					
										$valid=0;
								}
						}
		
				}
				
		
		
		
				
		
		$succ=0;
		if($_POST['task']=="common_for_all")
		{
			
				if($valid==1)
				{
						$succ=1;
			
						//$ldid, $pldid different,,,,,,,,     single payment entry
						//EXTRACTING LDID
						$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['ldname']}'");
						if(!$result)
						{
								echo("Error in Query Execution");
								$succ=0;
						}
						$arr=mysql_fetch_array($result);
			
						$ldid=$arr['id'];
			
		
		
						//EXTRACTING PLDID
						$result=mysql_query("select * from bs_ledgers where ldname='{$_POST['pldname']}'");
						if(!$result)
						{
								echo("Error in Query Execution");
								$succ=0;
						}
						$arr=mysql_fetch_array($result);
						$pldid=$arr['id'];
			
		
				
						//insert into payment book
			
						$result=mysql_query("INSERT INTO `bs_payment_book` (`id`,`ledger_id`, `description`,`amount`, `date`, `source_ledger_id`) VALUES (NULL,'{$ldid} ','{$_POST['desc']}','{$_POST['amount']}','{$date}','{$pldid}')");
						if(!$result)
						{
								echo("Error in Payment Book Insertion NONSCSD ".mysql_error());
									$succ=0;
						}
			
			

						$voucherid=mysql_insert_id();
			
						//credit source ledger =CASH/BANK PLDID
						$pldname="bs_ledger_".ereg_replace(" ","_",$_POST['pldname']);
						$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PAYMENT','{$voucherid}', '0.00','{$_POST['amount']}','{$date}')");			
						if(!$result)
						{
								echo("<br>Error in crediting source ledger, NONSCSD : ".mysql_error());
								$succ=0;
						}
			

						//debit party ledger =LDID
						$ldname="bs_ledger_".ereg_replace(" ","_",$_POST['ldname']);
						$result=mysql_query("INSERT INTO {$ldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PAYMENT','{$voucherid}', '{$_POST['amount']}','0.00','{$date}')");			
						if(!$result)
						{
								echo("<br>Error in debiting ledger, NONSCSD : ".mysql_error());
								$succ=0;
						}
		
				}//END OF VALID =1 
	
		} //END OF POST TASK = ADDFOR NON SC SD

		if($_POST['task']=="edit_common_for_all")
		{
				//strictly check that there must be no overriding of variables !!!
				
				$pid=$_POST['pid'];

				$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_payment_book where id='{$pid}'");
				if(!$result)
						echo("Error in Query Execution");
				$previous=mysql_fetch_array($result);
		
				
				$ldid=$previous['ledger_id'];
				$pldid=$previous['source_ledger_id'];
				$new_pldid=$_POST['pldid'];
				
				

			/*
			if there is any change
			{
				update payment book..			
			
				if change in pldid
				{
					delete from previous pldid
					entry in new pldid
				}
				{
					//no change in pldid
					//but there is another change
					so update in  pldid
				}
				
				
			}
		*/
		
				$change=1;
				if($previous['date']==$_POST['date'])
				{
						if((int)$previous['amount']==$_POST['amount'])
						{
								if($previous['description']==$_POST['desc'])
								{
										if($pldid==$new_pldid)
										{
												$change=0;
												echo "No Alteration Performed!";
										}
								}
						}
				}
							
//				$valid=0;//temp
				if($valid==1 && $change==1)
				{
							//we are here it means...there is any change
							$succ=1;
							//update payment book.
							
							
							//same query again! must be global 
	
							$result=mysql_query("select *,DATE_FORMAT(date,'%d-%m-%Y') as date from bs_payment_book where id='{$pid}'");
		
							if(!$result)
									echo("Error in Query Execution");
							$previous=mysql_fetch_array($result);
			
							$result=mysql_query("UPDATE `bs_payment_book` as p SET p.description='{$_POST['desc']}',p.amount='{$_POST['amount']}' , p.date='{$date}',p.source_ledger_id='{$new_pldid}' WHERE p.id = '{$pid}' ");
				
							if(!$result)
							{
									echo("Error in Payment Book Alteration : ".mysql_error());
									$succ=0;
							}
					

			
			
			
							if($previous['source_ledger_id']!=$new_pldid)
							{
									//delete in one-------add in another
				
				
									//delete from previous
											//1. extract previous pldname
											$result=mysql_query("select ldname from bs_ledgers where id='{$previous['source_ledger_id']}'");
											if(!$result)
													echo("Error in Query Execution");
											$arr=mysql_fetch_array($result);
											$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					

					
											//2. delete from previous ldname
													//first fetch the id!!!
													$result=mysql_query("select id from {$pldname} where voucher_type='PAYMENT' and voucher_id='{$pid}' ");
													if(!$result)
													{
															echo("Error");
															$succ=0;
													}
													$arr=mysql_fetch_array($result);
							
													$result=mysql_query("delete from {$pldname} where id='{$arr['id']}'" );			
													if(!$result)
													{
																echo("Error in previous Ledger deletion".mysql_error());
																$succ=0;
													}				
					
									//add in new (credit source ledger)
									//1. extract new pldname
									$result=mysql_query("select ldname from bs_ledgers where id='{$new_pldid}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
									//2. insert in new 
									//credit party ledger
									$result=mysql_query("INSERT INTO {$pldname} (id,voucher_type,voucher_id,debit,credit,date) VALUES (NULL,'PAYMENT','{$pid}', '0.00','{$_POST['amount']}','{$date}')");			
									if(!$result)
									{
											echo("Error in Crediting Source Ledger Insertion".mysql_error());
											$succ=0;
									}
					

					
							}
							else
							{
									//update in one
					
									//1. extract previous=new pldname (credited)
									$result=mysql_query("select ldname from bs_ledgers where id='{$previous['source_ledger_id']}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$pldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
									$result=mysql_query("UPDATE {$pldname} as p SET p.credit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='PAYMENT' and p.voucher_id = '{$pid}' LIMIT 1 ");
									if(!$result)
									{
											echo("Error in Credited Alteration");
											$succ=0;
									}
		
							}
							
									//update in ldid.....no condition
					
									//1. extract previous=new ldname (debited)
									$result=mysql_query("select ldname from bs_ledgers where id='{$previous['ledger_id']}'");
									if(!$result)
											echo("Error in Query Execution");
									$arr=mysql_fetch_array($result);
									$ldname="bs_ledger_".ereg_replace(" ","_",$arr['ldname']);
					
				
									$result=mysql_query("UPDATE {$ldname} as p SET p.debit='{$_POST['amount']}' , p.date='{$date}' WHERE p.voucher_type='PAYMENT' and p.voucher_id = '{$pid}' LIMIT 1 ");
									if(!$result)
									{
											echo("Error in Debited Alteration");
											$succ=0;
									}
					}//END OF VALID=1
		

		} //END OF POST TASK = edit_common_for_all


		
			if($succ==1)
					echo"<br>SuccessFul";
			else
					echo"<br>Operation Fail";
		
	}//end of else part of addform2 i.e. to add information in database	
	
	
}//END OF ISSET POST


include_once($_SERVER['DOCUMENT_ROOT'].'/bs/include/footer.inc');
?>


